<?php
namespace app\common\libs;

use \app\common\libs\WeixinHelper;

class Tuling {
	var $type = 0;			// 输入类型:0-文本(默认)、1-图片、2-音频
	var $perception = [];

	function reply($wx_data) {
		switch (strtolower($wx_data['MsgType'])) {
			case 'voice':
				$this->voice();
				break;
			case 'image':
				$this->image($wx_data['PicUrl']);
				break;

			case 'text':
				$this->text($wx_data['Content']);
				break;

			default:
				$this->text(config('tuling.unknowtext'));
				break;
		}

		$this->userid($wx_data['FromUserName']);

		$params = $this->requestParams();
		$tuling_api = config('tuling.request_url');
	
		return $reply_message = \curlJson($tuling_api, $params);
	}

	/*
	 * $data 图灵的请求结果
	 * $touserid 微信的用户标识
	 */
	function toWXData($data, $toUserid) {
		$message = [];
		$url = '';
		foreach ($data['results'] as $key => $value) {
			switch ($value['resultType']) {
				case 'text':
					$message['text'] = [
					    "touser"=>$toUserid,
					    "msgtype"=>"text",
					    "text"=>
					    [
					         "content"=> $value['values']['text']
					    ]
					];
					break;
				
				case 'url':
					$url = "\n<a href=\"{$value['values']['url']}\">打开页面</a>";
					break;

				case 'news':
					break;

				case 'image':
					$media_id = WeixinHelper::addTmpImg($value['values']['image'], \token());

					$message['image'] = [
					    "touser"=>$toUserid,
					    "msgtype"=>"image",
					    "image"=>
					    [
					         "media_id"=>$media_id,
					    ]
					];
					break;
			}
		}

		if(!empty($url)) {
			$message['text']['text']['content'] .= $url; 
		}

		return array_values($message);
	}

	private function voice() {
		$this->type = 0;
		$this->perception['inputText'] = ['text' => ''];
	}

	private function image($url) {
		$this->type = 1;
		$this->perception['inputImage'] = ['url' => $url];
	}

	private function text($text) {
		$this->type = 0;
		$this->perception['inputText'] = ['text' => $text];
	}

	private function userid($userid) {
		$this->userid = $userid;
	}

	private function requestParams() {
		$params = [
			'reqType' => $this->type,
			'perception' => $this->perception,
			'userInfo' => [
		        'apiKey' => config('tuling.apiKey'),
		        'userId' => $this->userid,
		    ]
		];
		return $params;
	}
}